package com.chezai.client.dao.manager;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.chezai.client.bean.UserInfo;
import com.chezai.client.dao.DaoManager;
import com.chezai.client.dao.UserInfoDao;
import com.chezai.client.utils.TUtil;
import com.jx.driving.response.Terminal0x8703Response;
import com.orhanobut.logger.Logger;

import org.greenrobot.greendao.Property;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 用户信息数据操作管理类
 * Created by likunyang on 2017/8/29.
 */

public class UserInfoDaoManager {
    private static UserInfoDaoManager newInstance;
    private String TAG = this.getClass().getSimpleName();
    private UserInfoDao userInfoDao;
    private UserInfo mUserInfo;

    private UserInfoDaoManager() {
        userInfoDao = DaoManager.getInstance().getDaoSession().getUserInfoDao();
    }

    public static UserInfoDaoManager getInstance() {
        if (newInstance == null) {
            newInstance = new UserInfoDaoManager();
        }
        return newInstance;
    }

    public UserInfoDao getUserInfoDao() {
        return userInfoDao;
    }

    /**
     * 是否有相关身份证信息的用户
     *
     * @param IDCardNum 身份证号
     * @return true 有，false 无
     */
    public boolean isHaveUserInfo(String IDCardNum) {
        return findUserInfo(IDCardNum) != null;
    }

    public List<UserInfo> findUserInfoByType(int userType) {
        List<UserInfo> list = userInfoDao.queryBuilder().where(UserInfoDao.Properties.UserType.eq(userType)).list();
        return list;
    }

    /**
     * 通过用户_id，查找用户
     *
     * @param _Id
     * @return
     */
    public UserInfo findUserInfoById(long _Id) {
        if (mUserInfo != null && _Id == mUserInfo.get_ID()) {
            return mUserInfo;
        } else {
            mUserInfo = userInfoDao.load(_Id);
            return mUserInfo;
        }
    }

    /**
     * 通过用户身份证号，查找用户
     *
     * @param IDCardNum 身份证号
     * @return
     */
    public UserInfo findUserInfo(@NonNull String IDCardNum) {
        if (TextUtils.isEmpty(IDCardNum))
            throw new IllegalArgumentException("Can't empty or null find user info the arg IDCardNum ");
        UserInfo userInfo = userInfoDao.queryBuilder().where(UserInfoDao.Properties.IDCardNum.eq(IDCardNum)).unique();
        if (userInfo != null) {
            return userInfo;
        }
        return null;
    }

    public void update(UserInfo userInfo) {
        if (userInfo.get_ID() != null && mUserInfo != null && mUserInfo.get_ID() == userInfo.get_ID()) {
            mUserInfo = userInfo;
        }
        userInfoDao.update(userInfo);
    }

    /**
     * 插入用户信息，如果数据库中已经存在，则查找并返回库中信息
     *
     * @param IDCardNum 用户身份证号
     * @return
     */
    public UserInfo insertUserInfoOrFind(String IDCardNum) {
        UserInfo userInfo;
        if (!isHaveUserInfo(IDCardNum)) {
            userInfo = new UserInfo();
            userInfo.setIDCardNum(IDCardNum);
            long userId = userInfoDao.insert(userInfo);
            userInfo.set_ID(userId);
        } else {
            userInfo = findUserInfo(IDCardNum);
        }
        return userInfo;
    }

    /**
     * 插入用户信息
     *
     * @param IDCardNum  身份证号
     * @param unifiedNum 统一用户编号
     * @param ox8703     用户信息响应
     * @param userType
     */
    public void insertUserInfo(String IDCardNum, String unifiedNum, @NonNull Terminal0x8703Response ox8703, int userType) {
        if (ox8703 != null && !isHaveUserInfo(IDCardNum)) {
            UserInfo userInfo = new UserInfo();
            userInfo.setName(ox8703.getName());
            userInfo.setPhone(ox8703.getPhone());
            userInfo.setPhotoUrl(ox8703.getPhotoUrl());
            userInfo.setSex(ox8703.getSex());
            userInfo.setDrivingType(ox8703.getDrivingType());
            userInfo.setIDCardNum(IDCardNum);
            userInfo.setUnifiedNum(unifiedNum);
            userInfo.setUserType(userType);
            userInfoDao.insert(userInfo);
        }
    }

    /**
     * 更新用户信息
     *
     * @param IDCardNum
     * @param userInfo
     */
    public void updateUserInfo(String IDCardNum, @NonNull UserInfo userInfo) {
        if (userInfo != null && isHaveUserInfo(IDCardNum)) {
            UserInfo tempUserInfo = findUserInfo(IDCardNum);
            String drivingType = userInfo.getDrivingType();
            if (!TextUtils.isEmpty(drivingType)) {
                tempUserInfo.setDrivingType(drivingType);
            }
            String idCardNum = userInfo.getIDCardNum();
            if (!TextUtils.isEmpty(idCardNum)) {
                tempUserInfo.setIDCardNum(idCardNum);
            }
            String name = userInfo.getName();
            if (!TextUtils.isEmpty(name)) {
                tempUserInfo.setName(name);
            }
            String phone = userInfo.getPhone();
            if (!TextUtils.isEmpty(phone)) {
                tempUserInfo.setPhone(phone);
            }
            String photoUrl = userInfo.getPhotoUrl();
            if (!TextUtils.isEmpty(photoUrl)) {
                tempUserInfo.setPhotoUrl(photoUrl);
            }
            int sex = userInfo.getSex();
            if (sex != 0) {
                tempUserInfo.setSex(sex);
            }
            String unifiedNum = userInfo.getUnifiedNum();
            if (!TextUtils.isEmpty(unifiedNum)) {
                tempUserInfo.setUnifiedNum(unifiedNum);
            }
            int userType = userInfo.getUserType();
            if (userType != 0) {
                tempUserInfo.setUserType(userType);
            }
            userInfoDao.update(tempUserInfo);
        }
    }

    /**
     * 更新用户信息
     * properties,values 两个参数不能为null
     * 并且两个参数的数组长度要相同，且要一一对应 key：values
     *
     * @param IDCardNum  身份证号，主要用于查找用户
     * @param properties 用户信息相关属性 UserInfoDao.Property
     * @param values     需要更新的值
     */
    public void updateUserinfoWithProperty(String IDCardNum, @NonNull Property[] properties, @NonNull Object[] values) {
        if (properties == null || values == null) {
            throw new IllegalArgumentException("the argument properties or values is null");
        }
        if (properties.length != values.length) {
            throw new IllegalArgumentException("the argument properties.length and values.length must be equals");
        }
        UserInfo tempUserInfo = findUserInfo(IDCardNum);
        if (tempUserInfo != null) {
            for (int i = 0; i < properties.length; i++) {
                try {
                    Method method = TUtil.getSetMethod(tempUserInfo.getClass(), properties[i].name, properties[i].type);
                    if (method != null) {
                        method.invoke(tempUserInfo, new Object[]{values[i]});
                    } else {
                        Logger.t(TAG).e("the property name <" + properties[i].name + "> not find in UserInfo class");
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            userInfoDao.update(tempUserInfo);
        }
    }
}
